package com.redlight.controller;

import com.redlight.base.*;
import com.redlight.exception.*;
import com.redlight.token.AccessToken;
import com.redlight.token.Audience;
import com.redlight.token.JwtHelper;
import com.redlight.token.LoginPara;
import com.redlight.token.valid.DefaultOauthTokenValid;
import com.redlight.token.valid.OauthTokenValid;
import com.redlight.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author chao
 * @Title: OauthToken
 * @date 2019-01-24 21:33
 */
@CrossOrigin
@RestController
@RequestMapping(value = "/api/sys/login")
public class OauthToken {
    @Autowired(
            required = false
    )
    private OauthTokenValid oauthTokenValid;

    public OauthToken() {
    }

//    @SaveLog("用户登录")
    @RequestMapping({"oauth/token"})
    public RestResult oauthToken( HttpServletRequest request) {
        LoginPara loginPara=new LoginPara();
        loginPara.setLoginName("admin");
        loginPara.setClientId("admin");
        loginPara.setPassword("123456");
        if (null == this.oauthTokenValid) {
            this.oauthTokenValid = new DefaultOauthTokenValid();
        }

        Audience audience = Audience.getInstance();
        String clientId = audience.getClientId();

        SysUser user;
        String accessToken;
        try {
            accessToken = loginPara.getLoginName();
            if (StringUtil.isBlank(accessToken)) {
                return new RestResult(ResultStatus.ACCOUNT_BLANK);
            }

            String password = loginPara.getPassword();
            if (StringUtil.isBlank(password)) {
                return new RestResult(ResultStatus.PASSWORD_BLANK);
            }

//            loginPara.setPassword(BtoAAtoB.atob(password));
            this.valid_client(clientId, loginPara);
            user = this.oauthTokenValid.valid(loginPara);
        } catch (OauthTokenException var15) {
            var15.printStackTrace();
            if (var15 instanceof InvalidClientException) {
                return new RestResult(ResultStatus.INVALID_CLIENTID);
            }

            if (var15 instanceof InvalidCaptchaException) {
                return new RestResult(ResultStatus.INVALID_CAPTCHA);
            }

            if (var15 instanceof InvalidPassException) {
                return new RestResult(ResultStatus.INVALID_PASSWORD);
            }

            if (var15 instanceof AccountDeniedException) {
                return new RestResult(ResultStatus.ACCOUNT_DENIED);
            }

            return new RestResult(false, "登录失败:" + var15.getMessage(), new Object[0]);
        }

        if (null == user) {
            return new RestResult(false, "登录失败:用户为null", new Object[0]);
        } else {
            try {
                accessToken = JwtHelper.createJWT(user.getId(), user.getLoginName(), clientId, audience.getName(), (long)audience.getExpiresSecond(), audience.getBase64Secret());
                AccessToken accessTokenEntity = new AccessToken(accessToken, audience.getTokenType());
                accessTokenEntity.setExpires_in((long)audience.getExpiresSecond());
//                Map<String, AccessToken> accessToken_thrds = new HashMap();
//                List<SysUserRel> sysUserRelList = this.oauthTokenValid.getSysUserRel(user.getId());
//                Iterator var10 = sysUserRelList.iterator();
//
//                while(var10.hasNext()) {
//                    SysUserRel sysUserRel = (SysUserRel)var10.next();
//                    AccessToken accessTokenThrd = new AccessToken();
//                    accessTokenThrd.setExpires_in((long)audience.getExpiresSecond());
//                    String tokenThrd = JwtHelper.createJWT(sysUserRel.getUserId2(), sysUserRel.getLoginName(), clientId, audience.getName(), (long)audience.getExpiresSecond(), audience.getBase64Secret());
//                    accessTokenThrd.setAuthorization(tokenThrd);
//                    accessTokenThrd.setToken_type(audience.getTokenType());
//                    accessToken_thrds.put("TOKEN@" + sysUserRel.getSys(), accessTokenThrd);
//                }

                RestResult restResult = new RestResult(ResultStatus.OK);
                restResult.put("message", "登录成功");
                restResult.put("accessToken", accessTokenEntity);
//                restResult.put("accessToken_thrds", accessToken_thrds);
                restResult.put("user", user);
                request.getSession().setAttribute("user", user);
                return restResult;
            } catch (Exception var14) {
                var14.printStackTrace();
                return new RestResult(false, "系统异常：" + var14.getMessage(), new Object[0]);
            }
        }
    }

//    @SaveLog("自动登录")
    @RequestMapping({"/api/oauth/refreshToken"})
    public RestResult refreshToken(HttpServletRequest request) {
        if (null == this.oauthTokenValid) {
            this.oauthTokenValid = new DefaultOauthTokenValid();
        }

        Audience audience = Audience.getInstance();
        String clientId = audience.getClientId();
        SysUser user = null;
        String userId = (String)request.getSession().getAttribute("SubjectId");

        try {
            String accessToken;
            if (StringUtil.isNotBlank(userId)) {
                user = this.oauthTokenValid.getUserById(userId);
            } else {
                accessToken = request.getParameter("loginName");
                if (StringUtil.isNotBlank(accessToken)) {
                    user = this.oauthTokenValid.getUserByLoginName(accessToken);
                }
            }

            if (null == user) {
                return new RestResult(false, "用户登录信息已失效,请重新登录", new Object[0]);
            } else {
                accessToken = JwtHelper.createJWT(user.getId(), user.getLoginName(), clientId, audience.getName(), (long)audience.getExpiresSecond(), audience.getBase64Secret());
                AccessToken accessTokenEntity = new AccessToken(accessToken, audience.getTokenType());
                accessTokenEntity.setExpires_in((long)audience.getExpiresSecond());
                Map<String, AccessToken> accessToken_thrds = new HashMap();
                List<SysUserRel> sysUserRelList = this.oauthTokenValid.getSysUserRel(user.getId());
                Iterator var10 = sysUserRelList.iterator();

                while(var10.hasNext()) {
                    SysUserRel sysUserRel = (SysUserRel)var10.next();
                    AccessToken accessTokenThrd = new AccessToken();
                    accessTokenThrd.setExpires_in((long)audience.getExpiresSecond());
                    String tokenThrd = JwtHelper.createJWT(sysUserRel.getUserId2(), sysUserRel.getLoginName(), clientId, audience.getName(), (long)audience.getExpiresSecond(), audience.getBase64Secret());
                    accessTokenThrd.setAuthorization(tokenThrd);
                    accessTokenThrd.setToken_type(audience.getTokenType());
                    accessToken_thrds.put("TOKEN@" + sysUserRel.getSys(), accessTokenThrd);
                }

                RestResult restResult = new RestResult(ResultStatus.OK);
                restResult.put("message", "登录成功");
                restResult.put("accessToken", accessTokenEntity);
                restResult.put("accessToken_thrds", accessToken_thrds);
                restResult.put("user", user);
                return restResult;
            }
        } catch (Exception var14) {
            var14.printStackTrace();
            return new RestResult(false, "系统异常：" + var14.getMessage(), new Object[0]);
        }
    }

    @RequestMapping({"/api/oauth/self"})
    public RestResult self(HttpServletRequest request) {
        try {
            if (null == this.oauthTokenValid) {
                this.oauthTokenValid = new DefaultOauthTokenValid();
            }

            SysUser user = null;
            String userId = (String)request.getSession().getAttribute("SubjectId");
            if (StringUtil.isNotBlank(userId)) {
                user = this.oauthTokenValid.getUserById(userId);
            }

            return null == user ? new RestResult(false, "登陆信息已失效,请重新登录", new Object[0]) : (new RestResult(true, "操作成功", new Object[0])).add("user", user);
        } catch (Exception var4) {
            var4.printStackTrace();
            return new RestResult(false, "系统异常：" + var4.getMessage(), new Object[0]);
        }
    }

    public void valid_client(String registClient, LoginPara loginPara) throws InvalidClientException {
        String clientId = loginPara.getClientId();
        if (StringUtil.isNotBlank(registClient) && (clientId == null || !registClient.equals(clientId))) {
            throw new InvalidClientException();
        }
    }

//    @SaveLog("用户登出")
    @RequestMapping({"oauth/logoff"})
    public RestResult logoff(HttpServletRequest request, HttpServletResponse response) {
        boolean flag = false;
        String ret = null;

        try {
            String userId = (String)request.getSession().getAttribute("SubjectId");
            UserUtils.removeCache(request, userId);//没有
        } catch (Exception var6) {
            var6.printStackTrace();
            ret = "系统异常：" + var6.getMessage();
        }

        return new RestResult(flag, ret, new Object[0]);
    }
}
